//
//  DIYLayout.swift
//  Pinterest
//
//  Created by GZOffice_hao on 2019/4/28.
//  Copyright © 2019 Razeware LLC. All rights reserved.
//

import UIKit

class DIYLayoutAttributes: UICollectionViewLayoutAttributes {
    var deltaY: CGFloat = 0
    override func copy(with zone: NSZone? = nil) -> Any {
        let attributes = super.copy(with: zone) as! DIYLayoutAttributes
        attributes.deltaY = deltaY
        return attributes
    }
    
    override func isEqual(_ object: Any?) -> Bool {
        if let attributes = object as? DIYLayoutAttributes {
            if attributes.deltaY == deltaY {
                return super.isEqual(object)
            }
        }
        return false
    }
}

class DIYLayout: UICollectionViewFlowLayout {
    
    var maximumStretchHeight: CGFloat = 0
    
    override class var layoutAttributesClass: AnyClass {
        return DIYLayoutAttributes.self
    }
    
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        let layoutAttributes = super.layoutAttributesForElements(in: rect) as? [DIYLayoutAttributes]
        guard let collectionView = collectionView, let attributes = layoutAttributes else { return layoutAttributes }
        
        let offset = collectionView.contentOffset
        var offsetY = offset.y
        if collectionView.insetsLayoutMarginsFromSafeArea {
            offsetY = offset.y + collectionView.safeAreaInsets.top
        }
        if offsetY < 0 {
            let deltaY = abs(offsetY)
            for att in attributes {
                if let kind = att.representedElementKind, kind == UICollectionView.elementKindSectionHeader {
                    var frame = att.frame
                    frame.size.height = min(max(headerReferenceSize.height, frame.height + deltaY), maximumStretchHeight)
                    frame.origin.y = frame.minY - deltaY
                    att.frame = frame
                    att.deltaY = deltaY
                }
            }
        }
        return attributes
    }
    
    override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
        return true
    }
}
